<template>
    <div class="user-info-box">
        <div class="section-title">头像设置</div>
        <div class="user-avatar">
            <Avatar
                :text="formProfile.username"
                :src="formProfile.avatar as string" 
                :size="150" 
            />
        </div>
        <el-upload
            class="upload-demo"
            drag
            :action="uploadUrl" 
            :headers="headers"
            method="post"
            :on-success="handleSuccess" 
            :on-error="handleError"    
            :before-upload="handleSelectFile"
            :show-file-list="false"
            >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
            将头像拖放到此处，或单击此处
            </div>
        </el-upload>
        <div class="section-title">资料设置</div>
        <el-form :model="formProfile" label-position="top">
            <el-row :gutter="30" justify="space-around">
                <el-col :md="10" :xs="24">
                    <el-form-item label="昵称 (非用户名)">
                        <el-input v-model="formProfile.nickname" :maxlength="20" />
                    </el-form-item>
                    <el-form-item label="学校">
                        <el-input v-model="formProfile.school" :maxlength="20" />
                    </el-form-item>
                </el-col>
                
                <el-col :md="10" :xs="24">
                    <el-form-item label="博客 ( 比如CSDN ) ">
                        <el-input v-model="formProfile.blog"/>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-radio-group v-model="formProfile.sex">
                            <el-radio label="男" value="男" border>男</el-radio>
                            <el-radio label="女" value="女" border>女</el-radio>
                            <el-radio label="保密" value="保密" border>保密</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row v-if="!loadingSaveBtn">
                <el-col :span="24">
                    <label class="el-form-item__label" style="float: none;">个性签名</label>
                    <MarkdownEidt v-model:content="formProfile.signature" />
                </el-col>
                <el-col :span="24" style="text-align: center;margin-top: 15px;">
                    <el-button
                        type="primary"
                        @click="handUpdateUserInfo"
                        :loading="loadingSaveBtn"
                        size="large"
                        >保存</el-button>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script setup lang="ts">
//import
import { onMounted, ref, defineAsyncComponent } from 'vue';
import { useUserStore } from '@/stores/user';
import { updateUserProfile } from '@/api/api';
import { ElMessage, ElNotification } from 'element-plus';
const Avatar=defineAsyncComponent(() => import('@/components/common/Avatar.vue'));
const MarkdownEidt=defineAsyncComponent(() => import('@/components/common/MarkdownEidt.vue'));

//data
const userStore=useUserStore();
interface FormProfile {
    username: string,
    nickname: string,
    school: string,
    blog: string,
    sex: string,
    signature: string,
    avatar: string,
}
//初始化表单数据 避免undefined
const formProfile=ref<FormProfile>({} as FormProfile);
const loadingSaveBtn=ref<boolean>(true);
//后端接口地址
const uploadUrl = '/api/user/upload-avatar';  
const headers={
    Authorization : userStore.token
};


//methods
onMounted(()=>{
    const userInfo=userStore.user;
    //浅拷贝
    Object.assign(formProfile.value, userInfo);
    loadingSaveBtn.value=false;
})


const checkFileType=(file:any)=> {
  if (!/\.(gif|jpg|jpeg|png|bmp|webp|GIF|JPG|PNG|WEBP)$/.test(file.name)) {
    ElNotification({
      title: "文件类型不支持",
      message: file.name + "不是正确格式的文件",
      type: 'warning',
    });
    return false;
  }
  return true;
}
const checkFileSize=(file:any)=>{
  // max size is 2MB
  if (file.size > 2 * 1024 * 1024) {
    ElNotification({
      title: "文件大小超过限制2Mb",
      message: file.name + "大小超过2Mb",
      type: 'warning',
    });
    return false;
  }
  return true;
}
const handleSelectFile=(file:any)=>{
  let isOk = checkFileType(file) && checkFileSize(file);
  if (!isOk) {
    return false;
  }
  return true;
}
//上传成功回调
const handleSuccess = (response: any, file: any) => {
    if(response.code===200){
        ElMessage.success(response.msg);
    }else{
        ElMessage.error(response.msg);
    }
};
//上传失败回调
const handleError = (err: any, file: any) => {
  console.log('上传失败', err);
  ElMessage.error("上传失败");
};
//更新用户信息
const handUpdateUserInfo=()=>{
    loadingSaveBtn.value=true;
    updateUserProfile({
        nickname: formProfile.value.nickname,
        school: formProfile.value.school,
        blog: formProfile.value.blog,
        sex: formProfile.value.sex,
        signature: formProfile.value.signature
    }).then(res=>{
        ElMessage.success(res.data.msg);
    }).catch(err=>{
        console.log(err);
    }).finally(()=>{
        loadingSaveBtn.value=false;
    })
}
</script>

<style lang="css" scoped>
.user-info-box{
    .upload-demo{
        width: 320px;
        margin: 0 auto;
        .el-icon--upload{
            color: #409eff;
        }
    }
    .user-avatar{
        text-align: center;
        margin-bottom: 10px;
    }
    .section-title {
        font-size: 22px;
        font-weight: 500;
        padding-top: 15px;
        padding-bottom: 20px;
        line-height: 30px;
        text-align: center;
    }
}
.md-editor{
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
:deep(.el-form-item__label) {
    font-size: 12px;
    line-height: 20px;
}
</style>
